<template>
	<view class="body">
		<scroll-view scroll-y="true" :scroll-top="scrollTop" @scrolltolower="loadMore" @scrolltoupper="refresh"
			scroll-with-animation="true" class="scroll-view">
			<!-- <view v-if="this.timeFrame == 1" class="dateText" @click="showCalendar()">
			{{$u.timeFormat(parentData.endTime, 'mm月dd日')}}
		</view>
		<view v-if="this.timeFrame != 1" class="dateText" @click="showCalendar()">
			{{$u.timeFormat(parentData.startTime, 'yyyy年mm月dd日')}}-{{$u.timeFormat(parentData.endTime, 'yyyy年mm月dd日')}}
		</view> -->
			<!-- <u-calendar v-model="showcalendar" :mode="mode" @change="Calendarchange"></u-calendar> -->
			<Draw ref="childRef" :text="''" :bg="'bg-aaa'" :line="'line-a'" @data-from-child="handleDataFromChild" />
			<lechart :parentData='parentData' :setFuTime='setTime' :gettongji='gettongji'></lechart>
			<view style="background-color: #f2f2f2;padding: 0 30rpx 30rpx">
				<view class="title">
					数据统计
				</view>
				<view class="info">
					<view class="container">
						<view class="list">
							<view class="time">
								<!-- <view class="yuan lv"></view> -->
								<image :src="$IMAGE_BASE_URL + '/img/new/xinlv.png'"
									style="width: 30rpx; height: 30rpx;margin:0rpx 10rpx; float: left;"></image>
								<!-- <image src="../../../img/new/xueya.png"
									style="width: 52rpx; height: 52rpx;margin:0rpx 10rpx; float: left;"></image> -->
								心率
								<text  v-if="timeFrame!=='day'" style="margin-left: auto; font-size: 12px;">正常：{{alarm.BPM.downBpm}} - {{alarm.BPM.upBpm}}</text>
							</view>
							<view v-if="timeFrame==='day'">
								<view class="data">
									{{items.length > 0?items[0].value:'--'}}<text>bpm</text>
								</view>
								<view class="fanwei">
									<view>{{interval.heartRate.minMinValue}}</view>
									<view>
										<image :src="$IMAGE_BASE_URL + '/img/new/xiegan.png'" style="width: 42rpx; height: 26rpx;"></image>
									</view>
									<view>{{interval.heartRate.maxMaxValue}}</view>
									<view class="danwei">bpm</view>
								</view>
							</view>
							<view v-else>
								<view class="data">
									{{interval.heartRate.minMinValue}} - {{interval.heartRate.maxMaxValue}}<text>bpm</text>
								</view>
							</view>
						</view>
						<!-- <view class="list" v-if="timeFrame === 'day'">
							<view class="time">
								<image :src="$IMAGE_BASE_URL + '/img/new/xinlv.png'"
									style="width: 30rpx; height: 30rpx;margin:0rpx 10rpx; float: left;"></image>
								心率变异性
								<view class="report" @click="jump('pages/Report/HR/index')">报告</view>
							</view>
							<view class="pilao">
								<view class="name">疲劳程度</view>
								<view class="state lvcolor">
									{{interval.fatigueResult?interval.fatigueResult:'暂无'}}
								</view>
							</view>
							<view class="pilao">
								<view class="name">房颤</view>
								<view class="state chengcolor">{{interval.afResult?interval.afResult:'暂无'}}
								</view>
							</view>
						</view> -->
					</view>
				</view>
			</view>
			<view style="background-color: #f2f2f2;padding: 0 30rpx 30rpx">
				<view class="title">
					数据详情
				</view>
				<view class="info">
					<view class="container">
						<!-- 下拉刷新容器 -->
						<!-- 刷新状态提示 -->
						<view v-if="refreshing" class="refreshing">正在刷新...</view>
						<!-- 列表项 -->
						<!-- <view class="list" >
							<view class="fl">{{$u.timeFormat(item.time*1, 'yyyy-mm-dd hh:MM:ss')}}</view>
							<view class="fr">
								<text v-if='item.value < alarm.down' class='red'>{{item.value}}</text>
								<text v-if='item.value > alarm.down'>{{item.value}}</text>
							</view>
						</view> -->
						
						<view class="list" v-if='items.length > 0' v-for="(item, index) in items" :key="index">
							<view class="time">
								<!-- <view class="yuan lv"></view> -->
								<image :src="$IMAGE_BASE_URL + '/img/new/xinlv.png'"
									style="width: 30rpx; height: 30rpx;margin:0rpx 10rpx; float: left;"></image>
								<!-- <image src="../../../img/new/xueya.png"
									style="width: 52rpx; height: 52rpx;margin:0rpx 10rpx; float: left;"></image> -->
								心率
								<text
									style="margin-left: auto; font-size: 12px;">{{$u.timeFormat(item.time*1, 'mm-dd hh:MM:ss')}}</text>
							</view>
							<view class="data2">
								{{item.value}}<text>bpm</text>
							</view>
							<view class="state2 red" v-if="item.value < alarm.BPM.downBpm">偏低</view>
							<view class="state2 red" v-else-if="item.value > alarm.BPM.upBpm">偏高</view>
							<view class="state2 lv" v-else>正常</view>
						</view>
						<!-- 加载状态提示 -->
						<view v-if="loading" class="loading">加载中...</view>
						<!-- 无更多数据提示 -->
						<view v-if="noMoreData" class="no-more-data">没有更多数据</view>
					</view>
				</view>
			</view>
		</scroll-view>
	</view>

</template>

<script>
	// 条件编译引入小程序专用代码
	import lechart from "../chart/index.vue";
	import * as echarts from '../components/echarts.esm.min.js'
	import {
		getStatistics,
		historyPropert,
		propertLast
	} from "../../../api/device/index.js";
	import {
		getCurrentPage
	} from '@/core/app'
	import StorageUtils from "../../../utils/StorageUtils";
	// import {DeviceBasicData} from '@/service/mqtt/DeviceConfig.js';
	// import drawVue from '../draw/draw.vue';
	import Draw from '@/pages/chart/draw/draw.vue';
	// import Draw2 from '@/pages/draw/draw2.vue';
	// import WebSocketClient from '@/service/mqtt/WebSocketClient';
	// import Config from '@/core/config'
	export default {
		components: {
			Draw,
			lechart,
		},
		data() {
			return {
				iotDeviceId: '',
				mode: 'date',
				opts: {},
				alarm: JSON.parse(StorageUtils.get('ALARM')),
				identifier: 'heartRate',//,afResult,fatigueResult
				deviceInfo: {
					connection: { //心率是否连接
						value: 0
					},
				},
				interval: {
					heartRate:{
						minMinValue: 0,
						maxMaxValue: 0,
					}
				},
				// afResult:'--',
				// fatigueResult:'--',
				timeFrame:'day',
				parentData: {
					identifier: 'heartRate',
					name: '心率',
					color: ["#f9025a", '#ffebf0', '#ffb8c9'],
					showDay: true,
				},
				items: [], // 列表数据
				refreshing: false, // 是否正在刷新
				loading: false, // 是否正在加载更多
				noMoreData: false, // 是否没有更多数据
				page: 0, // 当前页码
				scrollTop: 0, // 滚动条位置，用于重置滚动位置到顶部
			};
		},

		onReady() {
			this.iotDeviceId = getCurrentPage().query.iotDeviceId;
			// this.gethistoryPropert(this.iotDeviceId);
		},
		onLoad() {
			// this.loadData(); // 页面加载时获取初始数据
			// propertLast({
			// 	identifiers: this.identifier
			// }).then(res => {
			// 	const result = {};
			// 	for (const item of res.obj) {
			// 		result[item.key] = item;
			// 	}
			// 	this.deviceInfo = {
			// 		...this.deviceInfo,
			// 		...result
			// 	}
			// });

		},
		mounted() {

		},
		methods: {
			jump(url, data) {
				if (this.mqttPing) {
					clearInterval(this.mqttPing);
					this.simDevice.close();
				}
				this.$navTo(url, {
					...data
				}, )
			},
			
			// if (this.timeFrame == 'day') {
			// 	historyPropert({
			// 		startTime:this.startTime,
			// 		endTime: this.endTime,
			// 		current: 1,
			// 		size: 10000,
			// 		identifier: 'afResult,fatigueResult'
			// 	}).then(res => {
			// 		// 创建一个对象来统计每个key下的value出现的次数
			// 		const keyValueCount = {};
			// 		// 遍历数组，统计每个key下的value出现的次数
			// 		if(res.obj.records.length == 0){
			// 			this.interval = {
			// 				afResult:'--',
			// 				fatigueResult:'--',
			// 			}
			// 			return false;
			// 		}
			// 		res.obj.records.forEach(item => {
			// 		    const { key, value } = item;
			// 		    if (!keyValueCount[key]) {
			// 		        keyValueCount[key] = {};
			// 		    }
			// 		    if (keyValueCount[key][value]) {
			// 		        keyValueCount[key][value]++;
			// 		    } else {
			// 		        keyValueCount[key][value] = 1;
			// 		    }
			// 		});
			// 		// 找出每个key下出现次数最多的value
			// 		const result = {};
			// 		for (const key in keyValueCount) {
			// 		    let maxValue = null;
			// 		    let maxCount = 0;
			// 		    for (const value in keyValueCount[key]) {
			// 		        if (keyValueCount[key][value] > maxCount) {
			// 		            maxValue = value;
			// 		            maxCount = keyValueCount[key][value];
			// 		        }
			// 		    }
			// 		    result[key] = { value: maxValue, count: maxCount };
			// 		}
			// 		this.interval.afResult=result.afResult.value
			// 		this.interval.fatigueResult=result.fatigueResult.value
			// 	})
			// }
			//子传入的参数
			gettongji(res) {
				// 1. 收集所有数据的maxValue和minValue
				const typeValues = {};
				let interval = this.interval;
				// 遍历外层数组
				res.forEach(innerArray => {
					// 遍历内层数组的每个对象
					innerArray.forEach(item => {
						const {
							dataType,
							maxValue,
							minValue
						} = item;
						// 转换为数字类型
						const max = Number(maxValue);
						const min = Number(minValue);
			
						// 如果该类型尚未初始化，创建初始结构
						if (!typeValues[dataType]) {
							typeValues[dataType] = {
								maxValues: [],
								minValues: []
							};
						}
						// 收集最大值和最小值
						typeValues[dataType].maxValues.push(max);
						typeValues[dataType].minValues.push(min);
					});
				});
			
				// 2. 计算每个类型的maxMaxValue和minMinValue，并更新到interval
				Object.keys(interval).forEach(type => {
					if (typeValues[type]) {
						// 有对应数据：计算实际最大/最小值
						interval[type].maxMaxValue = Math.max(...typeValues[type].maxValues);
						interval[type].minMinValue = Math.min(...typeValues[type].minValues);
					} else {
						// 无对应数据：强制设为0（覆盖任何初始值）
						interval[type].maxMaxValue = 0;
						interval[type].minMinValue = 0;
					}
				});
			},
			setTime(startTime, endTime, isMonthly, timeFrame) {
				this.startTime = startTime
				this.endTime = endTime
				this.isMonthly = isMonthly
				this.timeFrame = timeFrame
				this.loadData(startTime, endTime, true);
				// this.gettongji();
				
					console.log(this.startTime);
			},
			loadData(startTime, endTime, refresh = false) {
				
					console.log(this.startTime);
				let deviceId = getCurrentPage().query.iotDeviceId
				if (refresh) {
					this.noMoreData = false
				}
				if (this.refreshing || this.loading||this.noMoreData) return;
				let isRefresh = refresh;
				if (refresh) {
					this.refreshing = true;
					this.page = 1; // 刷新时重置页码为1
					this.items = []; // 清空列表数据
				} else {
					this.loading = true;
					this.page += 1; // 加载更多时页码加1
				}
				historyPropert({
					deviceId,
					startTime: startTime ? startTime : this.startTime,
					endTime: endTime ? endTime : this.endTime,
					current: this.page,
					size: 20,
					identifier: this.parentData.identifier
				}).then(res => {
					res = res.obj
					let data = []
					res.records.map(val => {
						data.push(val)
					})
					if (data) {
						if (isRefresh) {
							this.items = data;
						} else {
							this.items = [...this.items, ...data];
						}
					}
					if(this.page > res.pages){
						this.noMoreData = true;
					}
					if (isRefresh) {
						this.refreshing = false;
						this.scrollTop = 0; // 刷新成功后重置滚动位置到顶部（如果需要）
					} else {
						
						this.loading = false;
					}
				}).catch(error => {
					console.log(error);
					if (isRefresh) {
						this.refreshing = false;
					} else {
						this.loading = false;
					}
					uni.showToast({
						title: '加载失败',
						icon: 'none',
					});
				});
			},
			// 下拉刷新
			refresh() {
				// this.loadData(true);
			},
			// 上拉加载更多
			loadMore() {
				this.loadData();
			},
		}
	}
</script>
<style lang="scss">
	.body {
		background-color: #f2f2f2;

		.container {
			// padding: 20px;
		}

		.scroll-view {
			height: 100vh;
			/* 或者其他你需要的高度 */
			overflow: hidden;
		}

		.item {
			padding: 10px;
			border-bottom: 1px solid #eee;
		}

		.refreshing,
		.loading {
			text-align: center;
			padding: 20px;
		}

		.no-more-data {
			text-align: center;
			padding: 20px;
			color: #999;
		}

		.title {
			font-size: 36rpx;
			line-height: 76rpx;
		}

		.info {
			margin-bottom: 10px;
			background-color: #fff;
			padding: 30rpx;
			border-radius: 30rpx;
			overflow: hidden;
			position: relative;
			font-size: 36rpx;

			.state2 {
				width: 72rpx;
				height: 36rpx;
				line-height: 36rpx;
				border-radius: 6rpx;
				position: absolute;
				top: 110rpx;
				right: 35rpx;
				font-size: 24rpx;
				color: #fff;
				text-align: center;
			}

			.data {
				font-size: 82rpx;
				font-weight: bold;
				line-height: 150rpx;
				float: left;

				text {
					padding-left: 10rpx;
					font-size: 26rpx;
				}
			}

			.data2 {
				font-size: 82rpx;
				font-weight: bold;
				line-height: 110rpx;
				text-align: center;

				text {
					padding-left: 10rpx;
					font-size: 26rpx;
				}
			}

			.fanwei {
				width: 100rpx;
				text-align: center;
				float: right;
				line-height: 36rpx;
				font-size: 36rpx;

				.danwei {
					font-size: 15.4rpx;
					color: #a0a0a0;
				}
			}

			.list {
				overflow: hidden;
				border-bottom: #f7f7f8 10rpx solid;
				padding-top: 30rpx;
				position: relative;

				.time {
					display: flex;
					line-height: 30rpx;
				}

				.report {
					margin-left: auto;
					font-size: 12px;
					background-color: #eee;
					line-height: 32rpx;
					border-radius: 16rxp;
					width: 100rpx;
					text-align: center;
					color: #09A052;
				}
			}

			.list:first-child {
				padding-top: 0;

				.state2 {
					top: 80rpx;
				}
			}

			.pilao {
				float: left;
				width: 50%;
				text-align: center;
				margin-top: 20rpx;

				.name {
					font-size: 26rpx;
				}

				.state {
					font-size: 45rpx;
					line-height: 50px;
					font-weight: bold;
					color: #bbbbbb;
				}
			}

			.list:last-child {
				border: none;
			}
		}

		.yuan {
			height: 30rpx;
			width: 30rpx;
			border-radius: 50%;
		}

		.lv {
			background-color: #0cd10f;
			margin-right: 10rpx;
		}

		.red {
			background-color: #ff2727;
		}

		.lvcolor {
			color: #0cd10f !important;
		}

		.chengcolor {
			color: #ffa126 !important;
		}

		.zi {
			background-color: #9270ff;
			margin-right: 10rpx;
		}
	}
</style>